<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * @category    CosmoCommerce
 * @package     CosmoCommerce_Alipay
 * @copyright   Copyright (c) 2009-2013 CosmoCommerce,LLC. (http://www.cosmocommerce.com)
 * @contact :
 * T: +86-021-66346672
 * L: Shanghai,China
 * M:sales@cosmocommerce.com
 */
class Jolly_Masa_PaymentController extends Mage_Core_Controller_Front_Action
{
    /**
     * Order instance
     */
    protected $_order;
	//protected $_gateway="https://mapi.alipay.com/gateway.do?";

    /**
     *  Get order
     *
     *  @param    none
     *  @return	  Mage_Sales_Model_Order
     */
    public function getOrder()
    {
        if ($this->_order == null)
        {
            $session = Mage::getSingleton('checkout/session');
            $this->_order = Mage::getModel('sales/order');
            $this->_order->loadByIncrementId($session->getLastRealOrderId());
        }
        return $this->_order;
    }

    /**
     * When a customer chooses Alipay on Checkout/Payment page
     *
     */
    public function redirectAction()
    {
        $session = Mage::getSingleton('checkout/session');
        $session->setJollyMasaPaymentQuoteId($session->getQuoteId());
		
        $order = $this->getOrder();		
        if (!$order->getId())
        {
            $this->norouteAction();
            return;
        }

        $order->addStatusToHistory(
        $order->getStatus(),
			Mage::helper('masa')->__('Customer was redirected to Masa')
        );
        $order->save();

        $this->getResponse()
        ->setBody($this->getLayout()
        ->createBlock('masa/redirect')
        ->setOrder($order)
        ->toHtml());

        $session->unsQuoteId();
    }

    public function notifyAction()
	{
		//通知回调地址，用于更新订单状态
		if ($this->getRequest()->isPost())
        {
            $postData = $this->getRequest()->getPost();
			$model = Mage::getModel('chinarate/shippingcompany');
            if($postData['resultCode'] == 10){
				//payment success
				$merchantOrderNo = $postData['merchantOrderNo'] ;//order_id
				//$masapayOrderNo  = $postData['masapayOrderNo']; //交易流水号
				//change order status
				$orderOBJ = Mage::getModel('sales/order');
				$orderOBJ->loadByIncrementId($merchantOrderNo);
				
				$state = Mage_Sales_Model_Order::STATE_PROCESSING;
				$orderOBJ->setStatus($state);
				$orderOBJ->setState($state);
				$orderOBJ->save();
				
				$amount = $postData['orderAmount'] ? $postData['orderAmount'] / 100 : 0;			
				$orderOBJ->addStatusHistoryComment(Mage::helper('sales')->__('Registered notification about captured amount of %s.', $amount),$state)
                ->setIsCustomerNotified(true)
                ->save();
				
				
				
				$data['resultCode'] =  $postData['resultCode'];
				$data['orderId'] = $merchantOrderNo;
				$data['result'] = serialize($postData);				
				$model = Mage::getModel('masa/masapayment')->setData($data);
				$model->save();
				echo "ok";
				
			}
			else if($postData['resultCode'] == 11){
				$data['resultCode'] =  $postData['resultCode'];
				$data['orderId'] = 0;
				$data['result'] = serialize($postData);				
				$model = Mage::getModel('masa/masapayment')->setData($data);
				$model->save();
				echo "error";
			}
			else{
				$data['resultCode'] =  12;
				$data['orderId'] = 0;
				$data['result'] = serialize($postData);				
				$model = Mage::getModel('masa/masapayment')->setData($data);
				$model->save();
				echo "error";
			}

        }
		else{
			$data['resultCode'] =  13;
			$data['orderId'] = 0;
			$data['result'] = serialize(array("message"=>"request method is error!"));				
			$model = Mage::getModel('masa/masapayment')->setData($data);
			$model->save();
			echo "error";
		}
		
		
	}
	
    
     /**
     *  Save invoice for order
     *
     *  @param    Mage_Sales_Model_Order $order
     *  @return	  boolean Can save invoice or not
     */
    protected function saveInvoice(Mage_Sales_Model_Order $order)
    {
        if ($order->canInvoice())
        {
            $convertor = Mage::getModel('sales/convert_order');
            $invoice = $convertor->toInvoice($order);
            foreach ($order->getAllItems() as $orderItem)
            {
                if (!$orderItem->getQtyToInvoice())
                {
                    continue ;
                }
                $item = $convertor->itemToInvoiceItem($orderItem);
                $item->setQty($orderItem->getQtyToInvoice());
                $invoice->addItem($item);
            }
            $invoice->collectTotals();
            $invoice->register()->capture();
            Mage::getModel('core/resource_transaction')
            ->addObject($invoice)
            ->addObject($invoice->getOrder())
            ->save();
            return true;
        }

        return false;
    }

    /**
     *  Success payment page
     *
     *  @param    none
     *  @return	  void
     */
    public function successAction()
    {
        $session = Mage::getSingleton('checkout/session');
        $session->setQuoteId($session->getJollyMasaQuoteId());
        $session->unsJollyMasaQuoteId();

        $order = $this->getOrder();

        if (!$order->getId())
        {
            $this->norouteAction();
            return;
        }

        
        $this->_redirect('checkout/onepage/success');
    }

    /**
     *  Failure payment page
     *
     *  @param    none
     *  @return	  void
     */
    public function errorAction()
    {
        $session = Mage::getSingleton('checkout/session');
        $errorMsg = Mage::helper('masa')->__(' There was an error occurred during paying process.');

        $order = $this->getOrder();

        if (!$order->getId())
        {
            $this->norouteAction();
            return;
        }
        if ($order instanceof Mage_Sales_Model_Order && $order->getId())
        {
            $order->addStatusToHistory(
            Mage_Sales_Model_Order::STATE_CANCELED,//$order->getStatus(),
            Mage::helper('masa')->__('Customer returned from Masa.').$errorMsg
            );

            $order->save();
        }

        $this->loadLayout();
        $this->renderLayout();
        Mage::getSingleton('checkout/session')->unsLastRealOrderId();
    }
	
	
	
}
